package com.edu.tool.util;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 操作数据库操作
 * <p>
 * Created by Liuzq on 2017/9/26.
 */
public class OperateDBUtil {

    /**
     * 创建数据库
     *
     * @param dbName 数据库名
     */
    public static void createDB( DataSource ds,String dbName) {



        Connection connection = null;
        Statement statement = null;
        try {
            connection = ds.getConnection();
            statement = connection.createStatement();

            String sql = "CREATE DATABASE IF NOT EXISTS " + dbName + " DEFAULT CHARACTER SET UTF8";

            statement.execute(sql);

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                statement.close();
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }
    }

    /**
     * 删除数据库
     *
     * @param dbName 数据库名字
     */
    public static void dropDB(DataSource ds,String dbName) {

        Connection connection = null;
        Statement statement = null;
        try {
            connection = ds.getConnection();
            statement = connection.createStatement();
            // 执行删除命令
            String sql = "DROP DATABASE IF EXISTS " + dbName;
            statement.execute(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                statement.close();
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
